<template>
  <!-- 权限检查：只有指定账号才能访问 -->
  <div v-if="!hasPermission" class="permission-denied">
    <div class="permission-content">
      <div class="permission-icon">🔒</div>
      <h2 class="permission-title">访问受限</h2>
      <p class="permission-message">此页面仅管理员等级访问</p>
      <div class="permission-actions">
        <a-button v-if="!userStore.isAuthenticated" type="primary" @click="openLoginDialog"> 登录账号 </a-button>
        <a-button v-else @click="goBack"> 返回上页 </a-button>
      </div>
    </div>
  </div>

  <!-- 用户管理页面 -->
  <div v-else class="user-management">
    <div class="header">
      <h2>用户管理</h2>
      <p class="description">管理系统中的所有用户账号</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="filter-section">
      <a-row :gutter="16">
        <a-col :span="8">
          <a-input v-model:value="searchKeyword" placeholder="搜索用户名或邮箱" allow-clear @pressEnter="loadUsers">
            <template #prefix>
              <SearchOutlined />
            </template>
          </a-input>
        </a-col>
        <a-col :span="6">
          <a-select v-model:value="statusFilter" style="width: 120px" placeholder="筛选状态" allow-clear @change="loadUsers">
            <a-select-option value="">全部状态</a-select-option>
            <a-select-option value="active">正常</a-select-option>
            <a-select-option value="banned">已封禁</a-select-option>
          </a-select>
          <a-button type="primary" @click="loadUsers" style="margin-left: 15px" :loading="loading">
            <SearchOutlined />
            搜索
          </a-button>
        </a-col>
      </a-row>
    </div>

    <!-- 用户列表 -->
    <div class="table-section">
      <a-table :dataSource="users" :columns="columns" :loading="loading" :pagination="pagination" row-key="id" @change="handleTableChange">
        <!-- 自定义单元格渲染 -->
        <template #bodyCell="{ column, record }">
          <!-- 用户状态 -->
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 'active' ? 'green' : 'red'">
              {{ record.status === 'active' ? '正常' : '已封禁' }}
            </a-tag>
          </template>

          <!-- 邮箱验证状态 -->
          <template v-else-if="column.key === 'emailVerified'">
            <a-tag :color="record.emailVerified ? 'blue' : 'orange'">
              {{ record.emailVerified ? '已验证' : '未验证' }}
            </a-tag>
          </template>

          <!-- 创建时间 -->
          <template v-else-if="column.key === 'createdAt'">
            {{ new Date(record.createdAt).toLocaleString() }}
          </template>

          <!-- 更新时间 -->
          <template v-else-if="column.key === 'updatedAt'">
            {{ new Date(record.updatedAt).toLocaleString() }}
          </template>

          <!-- 操作列 -->
          <template v-else-if="column.key === 'action'">
            <a-space>
              <!-- 状态操作 -->
              <a-button v-if="record.status === 'active'" type="text" danger size="small" @click="showBanModal(record)" :disabled="record.username === 'woaichitudouo'"> 封禁 </a-button>
              <a-button v-else type="text" size="small" @click="handleUnbanUser(record)" :disabled="record.username === 'woaichitudouo'"> 解封 </a-button>

              <!-- 重置密码 -->
              <a-button type="text" size="small" @click="showResetPasswordModal(record)" :disabled="record.username === 'woaichitudouo'"> 重置密码 </a-button>

              <!-- 删除用户 -->
              <a-popconfirm
                title="确认删除用户？"
                :description="`删除用户 '${record.username}' 及其所有数据，此操作不可恢复！`"
                ok-text="确认删除"
                cancel-text="取消"
                ok-type="danger"
                @confirm="handleDeleteUser(record)"
                :disabled="record.username === 'woaichitudouo'"
              >
                <a-button type="text" danger size="small" :disabled="record.username === 'woaichitudouo'"> 删除 </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 封禁用户模态框 -->
    <a-modal :open="banModal.visible" title="封禁用户" @ok="handleBanUser" @cancel="banModal.visible = false" :confirmLoading="banModal.loading">
      <p>
        确定要封禁用户 <strong>{{ banModal.user?.username }}</strong> 吗？
      </p>
      <a-form layout="vertical">
        <a-form-item label="封禁原因（可选）">
          <a-textarea v-model:value="banModal.reason" placeholder="请输入封禁原因..." :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 重置密码模态框 -->
    <a-modal :open="resetPasswordModal.visible" title="重置用户密码" @ok="handleResetPassword" @cancel="resetPasswordModal.visible = false" :confirmLoading="resetPasswordModal.loading">
      <p>
        为用户 <strong>{{ resetPasswordModal.user?.username }}</strong> 重置密码
      </p>
      <a-form layout="vertical">
        <a-form-item
          label="新密码"
          :rules="[
            { required: true, message: '请输入新密码' },
            { min: 6, max: 20, message: '密码长度为6-20个字符' }
          ]"
        >
          <a-input-password v-model:value="resetPasswordModal.newPassword" placeholder="请输入新密码（6-20个字符）" />
        </a-form-item>
        <a-form-item>
          <a-checkbox v-model:checked="resetPasswordModal.sendEmail"> 发送邮件通知用户 </a-checkbox>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { SearchOutlined } from '@ant-design/icons-vue'
import { getUsersList, updateUserStatus, adminResetPassword, deleteUser } from '@/utils/api.js'
import { useUserStore } from '@/stores/user.js'
import { useRouter } from 'vue-router'
import './index.css'

// 用户状态管理
const userStore = useUserStore()
const router = useRouter()

// 访问权限控制
const ALLOWED_USERNAME = 'woaichitudouo'

/**
 * 检查用户是否有访问权限
 * 只有登录且用户名为指定账号的用户才能访问
 */
const hasPermission = computed(() => {
  return userStore.isAuthenticated && userStore.username === ALLOWED_USERNAME
})

// 响应式数据
const loading = ref(false)
const users = ref([])
const searchKeyword = ref('')
const statusFilter = ref('')

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
})

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
    width: 120
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
    width: 200
  },
  {
    title: '邮箱验证',
    key: 'emailVerified',
    width: 100
  },
  {
    title: '状态',
    key: 'status',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 160
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    key: 'updatedAt',
    width: 160
  },
  {
    title: '操作',
    key: 'action',
    width: 160
  }
]

// 封禁用户模态框
const banModal = reactive({
  visible: false,
  loading: false,
  user: null,
  reason: ''
})

// 重置密码模态框
const resetPasswordModal = reactive({
  visible: false,
  loading: false,
  user: null,
  newPassword: '',
  sendEmail: false
})

// 加载用户列表
const loadUsers = async () => {
  if (!hasPermission.value) return

  loading.value = true
  try {
    const response = await getUsersList({
      page: pagination.current,
      limit: pagination.pageSize,
      status: statusFilter.value,
      search: searchKeyword.value
    })

    users.value = response.data.list
    pagination.total = response.data.pagination.total
  } catch (error) {
    message.error(error.message || '获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 处理表格变化
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadUsers()
}

// 显示封禁模态框
const showBanModal = (user) => {
  banModal.user = user
  banModal.reason = ''
  banModal.visible = true
}

// 封禁用户
const handleBanUser = async () => {
  banModal.loading = true
  try {
    await updateUserStatus(banModal.user.id, {
      status: 'banned',
      reason: banModal.reason
    })

    message.success(`用户 ${banModal.user.username} 已被封禁`)
    banModal.visible = false
    loadUsers() // 刷新列表
  } catch (error) {
    message.error(error.message || '封禁用户失败')
  } finally {
    banModal.loading = false
  }
}

// 解封用户
const handleUnbanUser = async (user) => {
  try {
    await updateUserStatus(user.id, {
      status: 'active',
      reason: '管理员解封'
    })

    message.success(`用户 ${user.username} 已被解封`)
    loadUsers() // 刷新列表
  } catch (error) {
    message.error(error.message || '解封用户失败')
  }
}

// 显示重置密码模态框
const showResetPasswordModal = (user) => {
  resetPasswordModal.user = user
  resetPasswordModal.newPassword = ''
  resetPasswordModal.sendEmail = false
  resetPasswordModal.visible = true
}

// 重置用户密码
const handleResetPassword = async () => {
  if (!resetPasswordModal.newPassword) {
    message.error('请输入新密码')
    return
  }

  if (resetPasswordModal.newPassword.length < 6 || resetPasswordModal.newPassword.length > 20) {
    message.error('密码长度为6-20个字符')
    return
  }

  resetPasswordModal.loading = true
  try {
    await adminResetPassword(resetPasswordModal.user.id, {
      newPassword: resetPasswordModal.newPassword,
      sendEmail: resetPasswordModal.sendEmail
    })

    message.success(`用户 ${resetPasswordModal.user.username} 的密码已重置`)
    resetPasswordModal.visible = false
  } catch (error) {
    message.error(error.message || '重置密码失败')
  } finally {
    resetPasswordModal.loading = false
  }
}

/**
 * 打开登录对话框
 * 通过派发自定义事件通知App.vue组件
 */
const openLoginDialog = () => {
  // 派发自定义事件到全局，让App.vue监听并打开登录对话框
  window.dispatchEvent(new CustomEvent('openLogin'))
}

/**
 * 返回上一页
 */
const goBack = () => {
  router.back()
}

/**
 * 删除用户
 */
const handleDeleteUser = async (user) => {
  try {
    await deleteUser(user.id, { confirm: true })
    message.success(`用户 ${user.username} 已被删除`)
    loadUsers() // 刷新列表
  } catch (error) {
    message.error(error.message || '删除用户失败')
  }
}

// 组件挂载时加载数据
onMounted(() => {
  if (hasPermission.value) {
    loadUsers()
  }
})
</script>
